import 'package:aichat_flutter_wallet/module_common/mpc_help/mpcManager.dart';
import 'package:aichat_flutter_wallet/module_common/utils/util.dart';
import 'package:flutter/material.dart';
import 'package:lib_database/lib_database.dart';
import 'package:lib_util/lib_util.dart';
import '../../../kai_print.dart';
import '../../../module_common/bridge/native_channel_bridge.dart';
import 'package:lib_network/lib_network.dart';

import '../../../module_common/mpc_help/createWalletTool.dart';
import '../../../module_common/network/http_api.dart';
import '../../../module_common/provider/nav_key.dart';
import '../../../module_common/provider/wallet_info_provider.dart';
import '../../../module_common/widgets/dialog/kai_bottom_tip_dialog.dart';
import '../model/wallet_list_model.dart';

class WalletIndexProvider extends ChangeNotifier {
  static late BuildContext pageContext;

  late bool hasSetPassword;

  bool isLoading = false;
  bool isSetWallet = false;
  late List<Wallet> walletList;




  bool isSetPassword() {
    final userId = NativeChannelBridge.instance.appCommMsg?.userId ?? '';
    UserSettings? isHasPass =
        ObjectBox().userSettingsModel.getUserSettingsByUId(userId);
    if (isHasPass != null) {
      hasSetPassword =
          isHasPass.password != null ? isHasPass.password!.length > 0 : false;
    } else {
      hasSetPassword = false;
    }
    return hasSetPassword;
  }

  WalletIndexProvider() {
    // isSetWallet = hasWallet();
  }

  // 重 新生成钱包 钱包
  Future<WalletInfo?> resetWallet(String key, bool isCreate,
      {bool? isServerBackUp,int? version=null}) async {
    try {
      List<Chain> chains = ChainList().chains;
      final userId = NativeChannelBridge.instance.appCommMsg?.userId;
      var salt = SP().getRandomSalt();
      List<WalletInfo> value;
      if (isCreate) {
        value = await createWalletTool().createWallet(key, chains, userId!,
            walletName: "MPC Wallet A",
            isMPC: true,
            salt: salt.toString(),
            backup: true,
            isServerBackUp: isServerBackUp);
      } else {
        value = await createWalletTool().createWatchWallet(
          key,
          chains,
          userId!,
          walletName: "MPC Wallet A",
          isMPC: true,
          salt: salt.toString(),
            version: version
        );
      }
      if (value.length <= 0) {
        throw Exception('Failed to generate wallet.Network configuration lost');
      }
      NavKey.getContext()
          .read<WalletInfoNotifier>()
          .updateCurrentWallet(value[0]);
      return value[0];
    } catch (e) {
      return null;
    }
  }

  // 检测感叹号
  Future<DialogType?> checkWalletStatusLocal() async {
    WalletCheckStatus walletCheckStatus =
        await WalletCheck().checkWalletExceptionLocal();
    Wallet? walletInfo = WalletCheck.getWalletInfo();
    if (walletInfo!.type == 2) {
      // 假设 他 上传 谷歌云端
      if (walletCheckStatus.serverIsUpload && walletCheckStatus.cloudIsUpload) {
        return DialogType.WALLET_ERROR;
      }
      // 假设 没有 销毁
      if (walletCheckStatus.serverIsUpload &&
          !walletCheckStatus.cloudIsUpload) {
        return DialogType.DELETE_WALLET;
      }
    } else {
      if (!walletCheckStatus.serverIsUpload ||
          !walletCheckStatus.cloudIsUpload) {
        return DialogType.RISK_SECURITY;
      }
    }

    return null;
  }

  Future<WalletInfo?> asyncGetServerKey() async {
    return WalletCheck.getServerKey().then((value) {
      if (value.$1.isEmpty) {
        return null;
      }
      // 发现 version == 1  version 0 是请求异常 ，version 应该是 2 才是正常；
      return mpcTool().getVersionFromFrag(value.$1).then((version){
        kaiPrint('current server mpc version $version');
        // 分片版本等 于1 去 除 tron 链 和 solana 链的生成
        return resetWallet(value.$1!, false,version:version);
      });
      return resetWallet(value.$1!, false);
    });
  }

  Future<WalletInfo?> checkInitWalletStatus() async {
    try {
      if (isLoading) {
        return null;
      }
      isLoading = true;
      // print('isLoading time ${isLoading}');
      return asyncGetServerKey().then((WalletInfo? walletInfo){
        isLoading = false;
        // print('isLoading time2 ${isLoading}');
        // print('checkInitWalletStatus walletInfo  $walletInfo');
        if (walletInfo != null) {
          updateInfo();
        }
      });
    } catch (e) {
      print('checkInitWalletStatus error : ${e.toString()}');
      isLoading = false;
      return null;
    }
  }

  // 初始化 状态 判断当前 钱包状态
  Future<DialogType?> checkWalletStatus(
      {WalletCheckStatus? walletCheckStatus, bool checkUpload = true}) async {
    try {
      // 获取 本地
      if (walletCheckStatus == null) {
        walletCheckStatus =
            await WalletCheck().checkWalletException(checkUpload: checkUpload);
      }
      print('walletCheckStatus?  ${walletCheckStatus == null}');
      walletErrorStatus pieceStatus = await WalletCheck().checkWalletStatus(
          walletCheckStatus: walletCheckStatus, checkUpload: checkUpload);
      print('pieceStatus $pieceStatus');
      Map<String, String?> keyMap =
          WalletCheck.resValueKey(walletCheckStatus.keyMap);

      // 备份弹窗
      if (checkUpload) {
        if (walletErrorStatus.serverNotUpload == pieceStatus ||
            walletErrorStatus.cloudNotUpload == pieceStatus) {
          return DialogType.RISK_SECURITY;
        }
      }

      // 重铸弹窗
      if (walletErrorStatus.localError == pieceStatus ||
          walletErrorStatus.serverError == pieceStatus ||
          walletErrorStatus.cloudError == pieceStatus) {
        String? pieceA = '';
        String? pieceB = '';
        String? pieceC = '';

        // 本地异常
        if (walletErrorStatus.localError == pieceStatus) {
          pieceA = keyMap['serverKey'];
          pieceB = keyMap['googleKey']!.isNotEmpty
              ? keyMap['googleKey']
              : keyMap['icloudKey'];
          pieceC = await mpcTool()
              .recoverMPCFragment(pieceA as String, pieceB as String);
          return DialogType.WALLET_ERROR;
        }
        // 服务端异常
        if (walletErrorStatus.serverError == pieceStatus) {
          pieceA = keyMap['localKey'];
          pieceB = keyMap['googleKey']!.isNotEmpty
              ? keyMap['googleKey']
              : keyMap['icloudKey'];
          pieceC = await mpcTool()
              .recoverMPCFragment(pieceA as String, pieceB as String);
          return DialogType.SERVER_SIDE_ERROR;
        }
        // 云端异常
        if (walletErrorStatus.cloudError == pieceStatus) {
          pieceA = keyMap['serverKey'];
          pieceB = keyMap['localKey'];
          pieceC = await mpcTool()
              .recoverMPCFragment(pieceA as String, pieceB as String);
          print('pieceC===${pieceC}');
          return DialogType.CLOUD_SIDE_ERROR;
        }
      }

      // 销毁弹窗, 观察者钱包
      if (walletErrorStatus.localAndCloudError == pieceStatus ||
          walletErrorStatus.localAndServerError == pieceStatus ||
          walletErrorStatus.cloudAndServerError == pieceStatus) {
        return DialogType.DELETE_WALLET;
      }
      return null;
    } catch (e) {
      print('checkWalletStatus $e');
      return DialogType.RISK_SECURITY;
    }
  }

  // 返回 钱包 是否存在
  Future<String?> fetchUserWalletByServer() async {
    try {
      var resp = await HttpManager().get(API.getWalletList, {});
      if (resp?.code != HttpConfig().successCode) {
        throw Exception('Failed to obtain server-side shards.');
      }
      var result = WalletListModel.fromJson(resp!.data!);
      if (result.list!.length <= 0) {
        return null;
      }
      return result.list!
          .firstWhereOrNull(
              (element) => element.status == 2 && element.import_type == 3)
          ?.public_key;
    } catch (e) {
      print('object $e');
      return null;
    }
  }

  // 返回 钱包 用户 id 通过 public_key
  Future<String> fetchUserOnePieceC() async {
    try {
      var resp = await HttpManager().get(API.getMpcSlice, {"wallet_id": '1'});
      if (resp?.code != HttpConfig().successCode) {
        throw Exception('Failed to obtain server-side shards.');
      }
      if (resp!.data['mpc'] == null || resp!.data['mpc'].length <= 0) {
        return '';
      }
      return resp!.data['mpc'];
    } catch (e) {
      print('object $e');
      return '';
    }
  }

  bool hasWallet() {
    return getWalletByUId() != null;
  }

  // 查询 本地钱包
  Wallet? getWalletByUId() {
    final userId = NativeChannelBridge.instance.appCommMsg?.userId;
    return ObjectBox().walletModel.getWalletByUId(userId!);
  }

  // 查询 本地钱包
  WalletInfo? getWalletInfoByUId(id) {
    return ObjectBox().walletInfoModel.getWalletInfoById(id);
  }

  List<Wallet> getWalletList() {
    walletList = ObjectBox().walletBox.getAll();
    return walletList;
  }

  init(BuildContext context) {
    pageContext = context;
  }

  void updateInfo() {
    isSetWallet = hasWallet();
    notifyListeners();
  }


// 创建wallet
}
